// pages/orderList/orderList.js
import Dialog from '@vant/weapp/dialog/dialog';
var app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    selectFlag: 0, // tab下标
    status: 0, // 请求类型 1 待发货 2待收货 3交易成功 4申请售后 5交易关闭
    pageNum: 1,
    risk: '', // 分享文案
    show1: false,
    timeList: [], // 倒计时列表
    orderList: [], // 订单列表
    noList: false
  },

  toOrderList() {
    let url = '/pages/orderList/orderList'
    wx.redirectTo({
      url
    })
  },

  toShopOrderList() {
    let url = '/pages/shopOrderList/orderList'
    wx.redirectTo({
      url,
    })
  },

  tabClick(e) {
    this.setData({
      status: e.currentTarget.dataset.status,
      selectFlag: e.currentTarget.dataset.selectflag,
      pageNum: 1,
      orderList: [],
      noList: false,
    })
    this.getOrdrList()
  },

  // 获取订单列表
  getOrdrList() {
    wx.showLoading({
      mask: true,
      title: '加载中…'
    })
    let api = ''
    if (this.data.status) {
      api = `${wx.api.presaletList}?orderStatus=${this.data.status}&pageNum=${this.data.pageNum}`
    } else {
      api = `${wx.api.presaletList}?&pageNum=${this.data.pageNum}`
    }
    wx.get(api, res => {
      wx.hideLoading()
      console.log('==== orderList ===', res)
      if (res.rows.length > 0) {
        this.setData({
          orderList: this.data.orderList.concat(res.rows)
        })
        this.singleCountDown(this.data.orderList)
      } else {
        if (this.data.pageNum > 1) {
          this.setData({
            noList: true
          })
        }
      }

    }, fail => {})
  },

  // 刷新页面数据
  refreshOrdrList() {
    this.setData({
      orderList: [],
      pageNum: 1,
      noList: false
    })
    this.getOrdrList()
  },

  singleCountDown(row) {
    let that = this
    let rows = row || that.data.orderList
    let timeList = []
    rows.forEach(item => {
      if (item.orderStatus == 0) {
        var endTime = new Date(item.expirationTime.replace(/-/g, "/")).getTime(); //结束时间时间戳
        var currentTime = new Date().getTime(); //当前时间时间戳
        var time = (endTime - currentTime) / 1000;
        // 商品已过购买期限
        if (time > 0) {
          var min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
          var sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
          item.lateTime = this.timeFormat(min) + ':' + this.timeFormat(sec)
        } else {
          item.lateTime = '00:00'
        }
        timeList.push(item.lateTime)
      } else {
        timeList.push('00:00')
      }
    })
    if (rows.filter(item => item.lateTime != '00:00').length > 0) {
      that.data.timeIntervalSingle ? clearTimeout(that.data.timeIntervalSingle) : ''; //清除定时器
      var timeIntervalSingle = setTimeout(that.singleCountDown, 1000);
      that.setData({
        timeIntervalSingle,
        timeList
      })
    } else {
      that.data.timeIntervalSingle ? clearTimeout(that.data.timeIntervalSingle) : ''; //清除定时器
      // that.setData({
      //   orderList: that.data.orderList.concat(rows)
      // })
    }
  },

  //时间显示小于10的前面补0方法
  timeFormat(param) {
    return param < 10 ? '0' + param : param;
  },

  // 跳转订单详情
  toDetail(e) {
    wx.navigateTo({
      url: `/pages/packageA/orderDetail/orderDetail?id=${e.currentTarget.dataset.id}`
    })
  },

  // 立即支付
  repay(e) {
    console.log('repay', e.currentTarget.dataset)
    if (e.currentTarget.dataset.orderstatus == 1 && e.currentTarget.dataset.presalestatus != 4) {
      return
    }
    wx.showLoading({
      mask: true
    })
    wx.get(`${wx.api.presaletPrepay}?orderNo=${e.currentTarget.dataset.orderno}&payType=1`, result => {
      console.log('==== prepay ===', result)
      wx.hideLoading()
      if (result.code == 200) {
        this.doWxPay(result)
      }
    })
  },

  // 小程序发起微信支付
  doWxPay(param) {
    let that = this
    wx.showLoading({
      mask: true
    })
    wx.requestPayment({
      timeStamp: param.data.timeStamp, //记住，这边的timeStamp一定要是字符串类型的，不然会报错
      nonceStr: param.data.nonceStr,
      package: param.data.package,
      signType: param.data.signType,
      paySign: param.data.paySign,
      success(event) {
        console.log('==== success ====', event);
        wx.showToast({
          title: '支付成功',
          icon: 'success',
          duration: 2000
        });
      },
      fail(error) {
        console.log('==== error ====', error)
        wx.showToast({
          title: '支付失败',
          icon: 'error',
          duration: 2000
        });
      },
      complete() {
        wx.hideLoading()
        console.log("pay complete")
        that.refreshOrdrList()
      }
    });
  },

  // 申请售后
  toAfter(e) {
    wx.setStorage({
      key: "afterDetail",
      data: e.currentTarget.dataset.item,
      success() {
        wx.navigateTo({
          url: '/pages/afterSales/afterSales?type=3'
        })
      }
    })
  },

  // 删除订单
  delOrder(e) {
    let that = this
    Dialog.confirm({
        title: '温馨提示',
        message: '是否删除该订单',
      })
      .then(() => {
        // on confirm
        wx.get(`${wx.api.presaletdelete}${e.currentTarget.dataset.id}`, res => {
          console.log('==== deleteOrder ===', res)
          if (res.code == 200) {
            that.refreshOrdrList()
          }
        }, fail => {})
      })
      .catch(() => {
        // on cancel
      });
  },

  // 修改地址
  setAddress(e) {
    wx.navigateTo({
      url: `../../addressList/addressList?fromType=yuSetAddress&id=${e.currentTarget.dataset.id}`
    })
  },

  // 取消订单
  cancelOrder(e) {
    let that = this
    let text
    if (e.currentTarget.dataset.orderstatus == 0) {
      text = '订单状况变化可能有延迟，如您已经付款，请稍等一段时间。请确认是否未付款并且不需要本商品？'
    } else {
      text = '选择退订退款后，订单将取消，退款将于10-30分钟内退回到您的支付账户。请确认是否退订退款？'
    }
    Dialog.confirm({
        title: '温馨提示',
        message: text,
      })
      .then(() => {
        // on confirm
        wx.showLoading({
          mask: true
        })
        wx.get(`${wx.api.presaletcancel}${e.currentTarget.dataset.id}`, res => {
          wx.hideLoading()
          console.log('==== deleteOrder ===', res)
          if (res.code == 200) {
            that.refreshOrdrList()
          }
        }, fail => {})
      })
      .catch(() => {
        // on cancel
      });
  },

  // 确认收货
  confirmSign(e) {
    let that = this
    wx.get(`${wx.api.presaletconfirmSign}${e.currentTarget.dataset.id}`, res => {
      console.log('==== deleteOrder ===', res)
      if (res.code == 200) {
        that.refreshOrdrList()
      }
    }, fail => {})
  },

  onClose1() {
    this.setData({
      show1: false
    });
  },

  onClose2() {
    this.setData({
      show2: false
    });
  },

  imageLoad() {
    console.info('==== 图片加载完成 ====')
    wx.hideLoading()
  },

  // 保存图片
  save() {
    let that = this
    wx.showLoading({
      mask: true
    })
    wx.getImageInfo({
      src: that.data.shareImg,
      success(ress) {
        console.log(ress)
        wx.saveImageToPhotosAlbum({
          filePath: ress.path,
          success(res) {
            wx.hideLoading()
            that.setData({
              show2: false
            })
            wx.showToast({
              title: '图片保存成功',
              icon: 'none',
              duration: 2000
            })
          }
        })
      }
    })
  },

  //  获取分享文案
  getRisk() {
    wx.get('/api/config/configKey?key=share_rule', res => {
      if (res.code == 200) {
        this.setData({
          risk: res.msg.replace(/\\n/g, "\n")
        })
      }
    }, fail => {})
  },

  // 点击分享按钮
  toshare(e) {
    let that = this
    Dialog.confirm({
        title: '温馨提示',
        message: that.data.risk,
      })
      .then(() => {
        that.setData({
          orderDetail: e.currentTarget.dataset.item,
          show1: true
        });
      })
      .catch(() => {
        // on cancel
      });
  },

  // 分享
  share(e) {
    let api = '/api/orders/'
    if (e.currentTarget.dataset.type == 'link') {
      api += `shareUrl?goodsId=${this.data.orderDetail.goodsId}&orderId=${this.data.orderDetail.id}&grouponNo=${this.data.orderDetail.grouponNo}`
    } else if (e.currentTarget.dataset.type == 'link_wb') {
      api += `shareUrl?goodsId=${this.data.orderDetail.goodsId}&orderId=${this.data.orderDetail.id}&grouponNo=${this.data.orderDetail.grouponNo}&urlType=1`
    } else {
      api += `shareImage?goodsId=${this.data.orderDetail.goodsId}&orderId=${this.data.orderDetail.id}&grouponNo=${this.data.orderDetail.grouponNo}`
    }
    wx.get(api, res => {
      console.log(e.currentTarget.dataset.type, res)
      if (res.code == 200) {
        if (e.currentTarget.dataset.type == 'link' || e.currentTarget.dataset.type == 'link_wb') {
          wx.setClipboardData({
            data: res.data.shareUrl,
            success(_res) {
              wx.getClipboardData({
                success(__res) {
                  console.log(__res.data) // data
                }
              })
            }
          })
        } else {
          wx.showLoading({
            mask: true
          })
          this.setData({
            shareImg: res.data.shareImg,
            show2: true,
            show1: false
          })
        }
      }
    }, fail => {})
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('==== options ====', options)
    if (options.status) {
      this.setData({
        selectFlag: options.selectflag,
        status: options.status
      })
    }
    this.data.pageNum = 1
    this.getOrdrList()
    this.getRisk()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    console.log(wx.getStorageSync('userInfo'))
    let that = this
    this.setData({
      userInfo: app.globalData.userInfo || wx.getStorageSync('userInfo')
    })
    wx.getStorage({
      key: "shopListRefresh",
      success(res) {
        console.info('==== shopListRefresh ====', res)
        if (res.data == 'true') {
          that.refreshOrdrList()
          wx.removeStorage({
            key: 'shopListRefresh',
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.data.noList) return
    this.data.pageNum++
    this.getOrdrList()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    if (this.data.orderDetail) {
      let orderDetail = this.data.orderDetail
      this.setData({
        orderDetail: '',
        show1: false,
      })
      return {
        title: orderDetail.goodsName,
        path: `/pages/detail/detail?id=${orderDetail.goodsId}&userId=${this.data.userInfo.id}&grouponNo=${orderDetail.grouponNo}`,
        imageUrl: orderDetail.goodsUrl
      }
    }
  }
})